package com.avalon.core.select.builder;

import com.avalon.core.condition.Condition;
import com.avalon.core.model.Record;
import com.avalon.core.model.RecordRow;
import com.avalon.core.select.TableFieldSection;
import com.avalon.core.service.AbstractService;
import com.avalon.core.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 树状结构 分页查询构建器 生存sql语句
 */
public class SelectTreeBuilder extends SelectPageBuilder {

    public SelectTreeBuilder(AbstractService service) {
        super(service);
    }

    public SelectTreeBuilder(SelectBuilder selectBuilder, Integer pageNum, Integer pageSize) {
        super(selectBuilder, pageNum, pageSize);
    }

    @Override
    public StringBuilder getSql() {
        return super.getSql();
    }

    /**
     * 增加父id的值
     *
     * @param parentIdRecord 里面需要有id的值
     */
    public void addParentPathCondition(Record parentIdRecord) {
        if (ObjectUtils.isNull(parentIdRecord) || parentIdRecord.isEmpty()) {
            return;
        }
        Condition idCondition = null;
        List<Object> parentIds = new ArrayList<>();
        Condition parentPathCondition = null;
        for (RecordRow row : parentIdRecord) {
            parentIds.add(row.getInteger("id"));
            if (ObjectUtils.isNull(parentPathCondition)) {
                parentPathCondition = Condition.likeCondition(getService().getParentPathField(),
                        "%," + row.getInteger("id") + ",%");
            } else {
                parentPathCondition = parentPathCondition.orLikeCondition(getService().getParentPathField(),
                        "%," + row.getInteger("id") + ",%");
            }
        }
        idCondition = Condition.inCondition(getService().getPrimaryKeyField(), parentIds);
        idCondition.orCondition(parentPathCondition);
        addCondition(idCondition);

    }

    /**
     * 获取第几页的主键列表
     *
     * @return
     */
    public StringBuilder getPageParentId() {
        StringBuilder sql = new StringBuilder();

        sql.append("select distinct id from ( ");
        sql.append("select id from ( ");
        sql.append(super.getAllSql());
        sql.append(" ) as p ");
        sql.append("union ");
        sql.append("select ").append(getService().getParentIdField().getFieldName()).append(" from ( ");
        sql.append(super.getAllSql());
        sql.append(" ) as y where y.").append(getService().getParentIdField().getFieldName()).append(" is not null ");
        sql.append(" ) as z ");

        if (getPageNum() != null && getPageSize() != null) {
            sql.append(" LIMIT ").append(getPageSize()).append(" OFFSET ")
                    .append((getPageNum() - 1) * getPageSize());
        }
        return sql;
    }
}
